import { userLogin } from "@/api/user/index";
import {
  removeToken,
  removeUserId,
  removeSchoolInfo,
  removeUserInfo,
  setToken,
  setUserInfo,
  setUserId,
} from "@/utils/author";

const user = {
  state: {
    token: '',
    openId: '123456',
    nickName: '李华',
    avatarUrl: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_OPEN_ID: (state, openId) => {
      state.openId = openId;
    },
    SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName;
    },
    SET_AVATAR_URL: (state, avatarUrl) => {
      state.avatarUrl = avatarUrl;
    },
  },
  actions: {
    Login({ commit }) {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: function (loginRes) {
            // 获取用户信息
            uni.getUserInfo({
              provider: "weixin",
              success: function (infoRes) {
                //使用获取的信息去后台服务器交换token
                userLogin(infoRes.userInfo).then((result) => {
                  //存储Token
                  const { token } = result;
                  const { openId, avatarUrl, nickName,schoolId } = result.data;
                  setToken(token);
                  setUserInfo(JSON.stringify(result.data));
                  setUserId(openId);
                  commit('SET_TOKEN', token);
                  commit('SET_OPEN_ID', openId);
                  commit('SET_NICK_NAME', nickName);
                  commit('SET_AVATAR_URL', avatarUrl);
                  resolve(schoolId);
                });
              },
              fail: function () {
                uni.showToast({
                  title: '获取用户信息失败!',
                  duration: 2000
                });
                commit('SET_TOKEN', '');
                commit('SET_OPEN_ID', '');
                commit('SET_NICK_NAME', '请登录!');
                commit('SET_AVATAR_URL', '');
                reject();
              },
            });
          },
        });
      })

    },
    GetInfo({ commit, state }) {

    },
    LogOut({ commit, state }) {

    },
    FedLogOut({ commit }) {
      removeToken();
      removeUserId();
      removeSchoolInfo();
      removeUserInfo();
      commit('SET_TOKEN', '');
      commit('SET_OPEN_ID', '');
      commit('SET_NICK_NAME', '请登录!');
      commit('SET_AVATAR_URL', '');
    }
  }

}

export default user
